package cn.git.shiro.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @description: RSA加解密工具类
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-01-05 08:58:58
 */
@Slf4j
@Component
public class DBRSAUtil {

    /**
     * 生成好公钥
     */
    public static final String PUB_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMZ/Q5CIvZjBTLD4sTwxbWYNNZWd7rImD+sAgwOAf+nH1vWN+Qk63iBGQYHzYK5EhSAFqsqX04lsTiJUH42YRJ9yIXUnvd6Osp2JYOXW8WTGgMtfDJp5WzbYzJRxQ0RmJNcfqMcHPVepgpjs2HNj59aTqNPLdiouRSRlh2E0umGwIDAQAB";

    /**
     * 生成好私钥
     */
    public static final String PRI_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIxn9DkIi9mMFMsPixPDFtZg01lZ3usiYP6wCDA4B/6cfW9Y35CTreIEZBgfNgrkSFIAWqypfTiWxOIlQfjZhEn3IhdSe93o6ynYlg5dbxZMaAy18MmnlbNtjMlHFDRGYk1x+oxwc9V6mCmOzYc2Pn1pOo08t2Ki5FJGWHYTS6YbAgMBAAECgYEAiQRNNXccmsDz7bGOZEumtrAor/Je8xFKnGCGrR+Q1aw7UHTnPvyO3JiyYUPcBkb+OF+2HPcNhzLCkXoQZltGlznwOwGvHl4qEheVAMwdgijuYQZpsiGQyVyr4C506ydoPjPXbWD+9GGLuakHtIlRP9FAGvwQe/5fkUYsiAJD8mkCQQDop8hxDCrsH9eBQ7PusaGjmW213zmX0O5yAntwuznX3zsQOo+AgeM00ottF4J5BXWCeyF5ZxKi6WoPjSgTw77fAkEAmn6QNwMSEbcWHbuaC3ofjcYhnOl47aQWNr+56G+Wc7vs4xs8PXdd3sVmlepOFSdJLWCxguUBO60Dg6cpnAFMRQJABZLPaHXkKVfx77TRgKxctPCeAjdgx9RHgg+xKVgy4IsGfTMJ8Qgriz5n/KsNgxywXfnZKXFgrupskgbNqPuNfQJAQlOjxnpi/4gCzrED6Xl8onk1ZRA3Ao83mjmlrsx5YyaDBN1kd18PxdwptqLo8tvy5rBkhTWb2erlX1gc3QURoQJABakHaa+GNmKyc7pasJHQ3HMR39k888TQPKEQiE461oc5//Cyqek7u91rCG0HR7O4Hk+ostH9lkxc4bG+HYgWgg==";

    /**
     * 加密类型RSA
     */
    public static final String RSA_TYPE = "RSA";

    /**
     * RSA
     * 算法名称/加密模式/数据填充方式
     */
    public static final String RSA_MODE = "RSA/ECB/PKCS1Padding";

    /**
     * 加密密匙
     */
    public static final String DB_LOCK_KEY = "DMZ:XdXt:loan==,";

    /**
     * RSA密钥长度
     */
    private static final Integer NUM_1024 = 1024;

    /**
     * RSA初始化key pair,初始化公钥私钥方法
     * @return KeyPair
     */
    public KeyPair getRSAKeyPair() {
        try {
            // 生成RSA密钥对
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance(RSA_TYPE);
            // 根据种子生成秘钥对,生成秘钥固定
            SecureRandom secureRandom = new SecureRandom(DB_LOCK_KEY.getBytes(StandardCharsets.UTF_8));
            keyGen.initialize(NUM_1024, secureRandom);
            return keyGen.generateKeyPair();
        } catch (Exception e) {
            String errorMsg = LogUtil.getStackTraceInfo(e, LogUtil.LENGTH_INT_2000);
            log.error(errorMsg);
            throw new RuntimeException("RSA初始化keyPairs失败");
        }
    }

    /**
     * RSA加密
     * @param data 待加密数据
     * @param publicKeyStr 公钥
     * @return 加密后的数据
     */
    public String encryptRSA(String data, String publicKeyStr) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(publicKeyStr);
            // 初始化公钥key
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_TYPE);
            PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

            // 使用公钥进行加密
            Cipher encryptCipher = Cipher.getInstance(RSA_MODE);
            encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes = encryptCipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            String errorMsg = LogUtil.getStackTraceInfo(e, LogUtil.LENGTH_INT_2000);
            log.error(errorMsg);
            throw new RuntimeException("RSA加密失败");
        }
    }

    /**
     * 进行RSA解密
     * @param content 解密文本
     * @param privateKeyStr 私钥字符串
     * @return
     */
    public String decryptRSA(String content, String privateKeyStr) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKeyStr);
            // 初始化私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_TYPE);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

            // 使用私钥进行解密
            Cipher decryptCipher = Cipher.getInstance(RSA_MODE);
            decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(content));
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            String errorMsg = LogUtil.getStackTraceInfo(e, LogUtil.LENGTH_INT_2000);
            log.error(errorMsg);
            throw new RuntimeException("RSA解密失败");
        }
    }

}

